<template>
  <basic-dialog
    :visible="show"
    minWidth="1000px"
    title="详情"
    :isShowClose="true"
    :isFullScreen="true"
    @close="$emit('close')"
  >
      <q-card-section class="flex" style="padding: 12px 20px 8px">
        <!-- 信息-->
        <div class="row flex" style="padding-top: 10px ">
          <div class="margin-b-10 w">操作人：{{detail.name}}</div>
          <div class="margin-b-10 w">部门/班组：{{detail.departmentName}}</div>
          <!-- <div class="margin-b-10 w">合格率：{{ detail.passRate  }}</div> -->
          <div class="margin-b-10 w">达成率：{{ detail.achievementRate  }}</div>
          <div class="margin-b-10 w">统计时间：{{selDate}}</div>
          <!-- <div class="margin-b-10 w">效能指数： {{detail.performanceIndex}}</div> -->
        </div>
<!--        <div class="items-center margin-t-10 form-inline no-padding" style="position: absolute; right: 20px"><q-btn class="btn "  outline :disable="!tableData.length" color="primary" label="导出Excel"  @click="exportExcel" /></div>-->
        <!-- 图表-->
        <q-table
          :data="tableData" :columns="tableColumns"
          row-key="id" class="myTable scroll"
          style="margin: 10px 0 20px 0; max-height: 350px; width: 100%"
          :pagination.sync="pagination" :hide-bottom="!!tableData.length"
          :loading="isTableLoading"
          color="primary"
        >
          <template v-slot:body-cell-productStandard="props">
            <td style="text-align: left">
              <td-spec :rowData="props.row"/>
            </td>
          </template>
        </q-table>
      </q-card-section>
  </basic-dialog>
</template>

<script>
import moment from 'moment'
import {
  getPerformanceDetail,
  downloadPerformanceDetail
} from '../../../boot/statistics/performance'
import { mapGetters } from 'vuex'
export default {
  name: 'performance-detail',
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    showItem: {
      required: true
    },
    showDate: {
      required: true
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  data () {
    return {
      requestId: null, // 导出唯一标识
      detail: {}, // 详情信息
      selDate: '', // 所选日期
      // 表格头部数据
      tableColumns: [
        { name: 'date', field: 'date', label: '日期', align: 'left' },
        { name: 'shiftName', field: 'shiftName', label: '班制', align: 'left' },
        { name: 'device', field: 'device', label: '加工设备', align: 'left' },
        { name: 'product', field: 'product', label: '加工产品', align: 'left' },
        { name: 'productStandard', field: 'productStandard', label: '产品规格', align: 'left' },
        { name: 'orderNumber', field: 'orderNumber', label: '订单号', align: 'left' },
        { name: 'workOrderId', field: 'workOrderId', label: '工单号', align: 'left' },
        { name: 'process', field: 'process', label: '工序', align: 'left' },
        { name: 'plannedQuantity', field: 'plannedQuantity', label: '计划数量', align: 'left' },
        { name: 'finishedQuantity', field: 'finishedQuantity', label: '完成数量', align: 'left' },
        { name: 'pieceUnitPrice', field: 'pieceUnitPrice', label: '工序单价（计件）', align: 'left' },
        { name: 'pieceRateWage', field: 'pieceRateWage', label: '计件工资', align: 'left' },
        { name: 'plannedDuration', field: 'plannedDuration', label: '计划工时', align: 'left' },
        { name: 'actualDuration', field: 'actualDuration', label: '实际工时', align: 'left' },
        { name: 'timeUnitPrice', field: 'timeUnitPrice', label: '工序单价（计时）', align: 'left' },
        { name: 'timeWage', field: 'timeWage', label: '计时工资', align: 'left' },
        { name: 'reportTypeLabel', field: 'reportTypeLabel', label: '工单类型', align: 'left' },
        { name: 'restDuration', field: 'restDuration', label: '休息时长(分钟)', align: 'left' }
        // { name: 'defectQuantity', field: 'defectQuantity', label: '不良数量', align: 'left' }
      ],
      // 表格内容
      tableData: [],
      // 表格分页配置
      pagination: {
        rowsPerPage: 0
      },
      // 表格正在加载
      isTableLoading: false,
      params: {}
    }
  },
  methods: {
    getDate (val) {
      return moment(val).format('YYYYMMDD')
    },
    // 导出Excel
    exportExcel () {
      let data = {
        excelHead: [],
        ...this.params
      }
      this.tableColumns.forEach(item => {
        data.excelHead.push(
          {
            field: item.name,
            name: item.label
          }
        )
      })
      this.$q.loading.show()
      // 需要传的是字符串类型，不然有可能报错
      const params = [{ name: String(this.detail.operatorId) }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      downloadPerformanceDetail(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getDate(this.showDate.split('~')[0])}-${this.getDate(this.showDate.split('~')[1])}-${this.detail.name}-人员绩效详情报表.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    // 获取人员绩效详情列表
    getPerformanceDetail (item, since, before) {
      let params = {
        operatorId: item.operatorId,
        before: before,
        since: since
      }
      this.params = params
      this.detail = item
      this.selDate = `${since} ~ ${before}`
      getPerformanceDetail(params).then(res => {
        this.tableData = res.data.map(v => {
          return {
            ...v,
            reportTypeLabel: v.reportType === 1 ? '手动报工' : '自动报工'
          }
        })
      })
    }
  }
}
</script>

<style scoped>
  .w{
    width: 320px
  }
</style>
